iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
自我挑戰組

Go to 放棄系列 第 19

go note => goroutine

  • 分享至 

  • xImage
  •  

今日main.go

package main

import "fmt"

func do(i int) {
	fmt.Println(i)
}

func main() {
	do(1)
	do(2)
	do(3)
}
package main

import (
	"fmt"
	"time"
)

func do(i int) {
	fmt.Println(i)
}

func main() {
	go do(1)
	go do(2)
	go do(3)
	time.Sleep(1 * time.Second)
}
package main

import (
	"fmt"
	"time"
)

func main() {
	msg := "Let 's Go"
	go func() {
		fmt.Println(msg)
	}()
	msg = "hey"
	time.Sleep(1 * time.Second)
}

會輸出"hey"
利用command

go run -race main.go

可以看到會檢查出哪些data有race condition
但用pi的環境 會出現下面的提示
go run: -race is only supported on linux/amd64, linux/ppc64le, freebsd/amd64, netbsd/amd64, darwin/amd64 and windows/amd64
改寫成

package main

import (
	"fmt"
	"time"
)

func main() {
	msg := "Let 's Go"
	go func(input string) {
		fmt.Println(input)
	}(msg)
	msg = "hey"
	time.Sleep(1 * time.Second)
}

把要輸出的變數丟到goroutine的argument

利用sync包的sync waitGroup 等待gorutine執行結束

package main

import (
	"fmt"
	"sync"
	"time"
)

func do(i int, wg *sync.WaitGroup) {
	fmt.Printf("start : %d\n", i)
	time.Sleep(1 * time.Second)
	fmt.Printf("end : %d\n", i)
	wg.Done() // 減掉完成的job數
}
func main() {
	wg := sync.WaitGroup{}
	wg.Add(3)
	go do(1, &wg)
	go do(2, &wg)
	go do(3, &wg)
	wg.Wait() // 等待 以便看結果
	fmt.Println("Done!!!!")
}

上一篇
go note => check code quality
下一篇
go note => existing docker set port and go flag
系列文
Go to 放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言